<template>
    <div class="login-container">
        <van-nav-bar title="登录" class="page-nav-bar" left-text="返回" left-arrow @click-left="$router.back()"/>

        <van-form @submit="onSubmit" ref="loginForm">
        <van-field
            v-model="user.mobile"
            name="mobile"
            placeholder="请输入手机号"
            left-icon="user-circle-o"
            :rules="userFormRules.mobile"
            type="number"
            maxlength="11"
        >
        <!-- left-icon仅支持vant内置的字体图标 -->
            <i slot="left-icon" class="toutiao toutiao-shouji"></i>
        </van-field>
        <van-field
            v-model="user.code"
            name="code"
            placeholder="请输入验证码"
            :rules="userFormRules.code"
            maxlength="6"
        >
            <i slot="left-icon" class="toutiao toutiao-yanzhengma"></i>
            <template #button>
                <van-count-down v-if="isCountDownShow" @finish="isCountDownShow=false" :time="1000*5" format="ss s"/>
                <van-button
                    v-else
                    class="send-sms-btn"
                    round size="small"
                    type="primary"
                    @click="onSendSms"
                    native-type="button"
                >
                <!-- native-type设置为button，防止触发表单提交，等价于preventDefault -->
                    发送验证码
                </van-button>
            </template>
        </van-field>
        <div class="login-btn-wrap">
            <van-button class="login-btn" round block type="info" native-type="submit">登录</van-button>
        </div>
        </van-form>
    </div>
</template>

<script>
import { login, sendSms } from '@/api/user'

export default {
    name: 'Login',
    data () {
        return {
            user: {
                mobile: '',
                code: ''
            },
            userFormRules: {
                mobile: [{
                    required: true,
                    message: '手机号不能为空'
                }, {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '手机号格式错误'
                }],
                code: [{
                    required: true,
                    message: '验证码不能为空'
                }, {
                    pattern: /^\d{6}$/,
                    message: '验证码格式错误'
                }]
            },
            isCountDownShow: false // 是否展示倒计时
        }
    },
    methods: {
        async onSubmit () {
            this.$toast.loading({
                message: '登录中...',
                forbidClick: true,
                // 禁用背景点击
                duration: 0
                // 持续时间，默认2000，如果为0则持续展示
            })

            try {
                const res = await login(this.user)
                // console.log('登录成功', res)
                this.$store.commit('setUser', res.data.data)
                this.$toast.success('登录成功')
                // 新的toast会顶掉原先的登录中
                this.$router.back()
            } catch (err) {
                if (err.response.status === 400) {
                    this.$toast.fail('手机号或验证码错误')
                } else {
                    this.$toast.fail('登录失败，请稍后重试', err)
                }
            }
        },
        async onSendSms () {
            try {
                // 校验手机号，会返回Promise对象
                await this.$refs.loginForm.validate('mobile')
                console.log('验证成功')
            } catch (err) {
                return console.log('验证失败', err)
                // 错误后直接返回，不会再向下执行
            }
            this.isCountDownShow = true
            try {
                await sendSms(this.user.mobile)
                this.$toast('发送成功')
            } catch (err) {
                this.isCountDownShow = false
                if (err.response.status === 429) {
                    this.$toast('发送太频繁，请稍后重试')
                } else {
                   this.$toast(('发送失败，请稍后重试', err))
                // this.$toast({message: err?.response?.data?.message || '发送失败'})
                // ?表示当前者不存在时返回undefined，而不会产生报错
                }
            }
        }
    }
}
</script>

<style scoped>
.toutiao {
    font-size: 37px;
}
.van-form {
    padding-top: 100px;
}
.send-sms-btn {
    width: 152px;
    height: 46px;
    line-height: 46px;
    font-size: 22px;
    color: #fff;
}
.login-btn-wrap {
    padding: 53px 33px;
}
.login-btn {
    background-color: #6db4fb;
    border: 0;
}
</style>
